<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://erdangjiade.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: xiaojie <997031758@qq.com>
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | 权限认证中间件
// +----------------------------------------------------------------------
namespace app\admin\middleware;

use app\admin\model\Admin;
use app\admin\model\AuthGroupAccess;
use app\admin\model\AuthRule;
use app\admin\model\Menu;

class Authenticate
{
    public function handle($request, \Closure $next)
    {
        if(Admin::userId() !== 1){
            $app = app('http')->getName();
            $controller = $request->controller(true);
            $action = $request->action(true);
            $allowUrl = [
                'admin/index/index',
                'admin/main/index',
            ];
            if(!in_array($app.'/'.$controller.'/'.$action,$allowUrl)){
                $group_ids = AuthGroupAccess::where('admin_id',Admin::userId())->column('auth_group_id');
                $rules = AuthRule::where('auth_group_id','in',$group_ids)->column('rule');
                $rule = Menu::where(['app'=>$app,'controller'=>$controller,'action'=>$action])->value('id');
                if(!in_array($rule,$rules)){
                    return view(':404');
                }
            }
        }

        return $next($request);
    }
}
